package goods

import (
	"Web-Shop/models"
	"log"
	"strconv"

	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
)

func (c *GoodsController) GoodsDetail() {
	c.Layout = "goodsLayout.html"
	c.TplName = "detail.html"
	id, err := c.GetInt(":id")
	if err != nil {
		c.Abort("404")
		return
	}
	goods := &models.GoodsSKU{Id: id}
	if goods, err = goods.Read(); err != nil {
		log.Println(err)
		c.Abort("505")
		return
	}
	goodsRecommend, err := goods.QueryRecommend(&models.GoodsType{Id: goods.GoodsType.Id})
	if err != nil {
		log.Println(err)
		c.Abort("505")
		return
	}
	if c.IsLogin {
		conn, err := redis.Dial("tcp", "47.111.181.52:6379")
		if err != nil {
			log.Println("redis连接失败")
		}
		defer conn.Close()
		conn.Do("lrem", "history_"+strconv.Itoa(c.User.Id), 0, id)
		conn.Do("lpush", "history_"+strconv.Itoa(c.User.Id), id)
	}
	GoodsTypes(&c.BaseController)
	c.Data["cartCount"] = c.GetCartCount()
	c.Data["goodsSKU"] = goods
	c.Data["goodsRecommend"] = goodsRecommend
}

func (c *GoodsController) ShowGoodsList() {
	c.Layout = "goodsLayout.html"
	c.TplName = "list.html"
	id, err := c.GetInt("typeId")
	sort := c.GetString("sort")
	if err != nil {
		c.Abort("404")
		return
	}
	goodsRecom, err := (&models.GoodsSKU{}).QueryRecommend(&models.GoodsType{Id: id})
	if err != nil {
		c.Abort("500")
		return
	}
	qs := models.QueryGoodsSKUsByType(&models.GoodsType{Id: id})
	switch sort {
	case "price":
		qs = qs.OrderBy("Price")
	case "sales":
		qs = qs.OrderBy("Sales")
	}
	if err != nil {
		c.Abort("500")
		return
	}
	var GoodsSKUs []*models.GoodsSKU
	GoodsTypes(&c.BaseController)
	c.Data["typeId"] = id
	c.Data["goodsRecom"] = goodsRecom
	c.Data["sort"] = sort
	c.SetObjectsWithLimit(qs, &GoodsSKUs, 2)
}

func (c *GoodsController) Search() {
	c.Layout = "goodsLayout.html"
	c.TplName = "search.html"

	goodsName := c.GetString("goodsName")

	GoodsTypes(&c.BaseController)

	var GoodsSKUs []models.GoodsSKU
	qs := orm.NewOrm().QueryTable("GoodsSKU")

	if goodsName == "" {
		c.SetObjectsWithLimit(qs, &GoodsSKUs, 2)
	} else {
		qs = qs.Filter("Name__icontains", goodsName)
		c.SetObjectsWithLimit(qs, &GoodsSKUs, 2)
	}
}
